<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="8">
        <div class="stat-card normal">
          <div class="stat-icon">
            <i class="el-icon-success"></i>
          </div>
          <div class="stat-content">
            <div class="stat-title">正常库存</div>
            <div class="stat-value">{{ statistics.normalProducts || 0 }}</div>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="stat-card warning">
          <div class="stat-icon">
            <i class="el-icon-warning"></i>
          </div>
          <div class="stat-content">
            <div class="stat-title">预警商品</div>
            <div class="stat-value">{{ statistics.warningProducts || 0 }}</div>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="stat-card danger">
          <div class="stat-icon">
            <i class="el-icon-error"></i>
          </div>
          <div class="stat-content">
            <div class="stat-title">缺货商品</div>
            <div class="stat-value">{{ statistics.outOfStockProducts || 0 }}</div>
          </div>
        </div>
      </el-col>
      <!-- <el-col :span="6">
        <div class="stat-card info">
          <div class="stat-icon">
            <i class="el-icon-data-line"></i>
          </div>
          <div class="stat-content">
            <div class="stat-title">健康度</div>
            <div class="stat-value">{{ Math.min(Math.max(statistics.avgHealthScore || 0, 0), 100) }}%</div>
          </div>
        </div>
      </el-col> -->
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>库存变动趋势</span>
          </div>
          <div id="trendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>预警商品</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="viewAllWarnings">查看全部</el-button>
          </div>
          <div class="warning-list">
            <div v-if="warningProducts && warningProducts.length > 0">
              <div v-for="item in warningProducts" :key="item.productId" class="warning-item">
                <div class="warning-info">
                  <div class="product-name">{{ item.productName }}</div>
                  <div class="stock-info">
                    <span :class="item.stockStatus === '3' ? 'danger' : 'warning'">
                      库存: {{ item.currentStock }} / 安全: {{ item.safetyStock }}
                    </span>
                  </div>
                </div>
                <div class="warning-status">
                  <el-tag :type="item.stockStatus === '3' ? 'danger' : 'warning'" size="mini">
                    {{ item.stockStatus === '3' ? '缺货' : '预警' }}
                  </el-tag>
                </div>
              </div>
            </div>
            <div v-else class="no-data">
              <i class="el-icon-info"></i>
              <p>暂无预警商品</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编码" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入商品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择商品分类" clearable>
          <el-option
            v-for="category in categoryOptions"
            :key="category.categoryId"
            :label="category.categoryName"
            :value="category.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brandId">
        <el-select v-model="queryParams.brandId" placeholder="请选择品牌" clearable>
          <el-option
            v-for="brand in brandOptions"
            :key="brand.brandId"
            :label="brand.brandName"
            :value="brand.brandId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['statistics:stock:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="stockList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品信息" align="center" min-width="180">
        <template slot-scope="scope">
          <div class="product-info">
            <div class="product-name">{{ scope.row.productName }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="SKU信息" align="center" min-width="220">
        <template slot-scope="scope">
          <div class="sku-info">
            <div class="sku-name">{{ scope.row.skuName || '默认规格' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="分类/品牌" align="center" width="150">
        <template slot-scope="scope">
          <div>{{ scope.row.categoryName }}</div>
          <div class="text-muted">{{ scope.row.brandName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="当前库存" align="center" width="100">
        <template slot-scope="scope">
          <span :class="getStockClass(scope.row)">{{ scope.row.currentStock }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安全库存" align="center" width="100" prop="safetyStock" />
      <el-table-column label="库存状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.stockStatus)" size="mini">
            {{ getStatusText(scope.row.stockStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120">
        <template slot="header">
          <span>健康度</span>
          <el-tooltip effect="dark" placement="top">
            <div slot="content">
              <div><strong>健康度计算公式：</strong></div>
              <div>• 当安全库存 > 0 时：健康度 = (当前库存 ÷ 安全库存) × 100%</div>
              <div>• 当安全库存 = 0 时：健康度 = 100%（默认值）</div>
              <br>
              <div><strong>健康度等级：</strong></div>
              <div style="color: #67C23A;">• 绿色（≥80%）：库存充足，无需补货</div>
              <div style="color: #E6A23C;">• 橙色（50%-79%）：库存预警，建议关注</div>
              <div style="color: #F56C6C;">• 红色（50%）：库存不足，需要补货</div>
              <br>
              <div>注意：健康度上限为100%</div>
            </div>
            <i class="el-icon-question" style="margin-left: 4px; color: #909399; cursor: pointer;"></i>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <el-progress
            :percentage="Math.min(Math.max(scope.row.healthScore || 0, 0), 100)"
            :color="getHealthColor(scope.row.healthScore)"
            :show-text="false"
            :stroke-width="8"
          ></el-progress>
          <div class="health-text">{{ Math.min(Math.max(scope.row.healthScore || 0, 0), 100) }}%</div>
          <div v-if="(scope.row.healthScore || 0) >= 100" class="health-tip" style="font-size: 10px; color: #909399;">
            库存极充足
          </div>
        </template>
      </el-table-column>
      <el-table-column label="近7天" align="center" width="120">
        <template slot-scope="scope">
          <div class="stock-change">
            <span class="in-stock">入: {{ scope.row.inStock7Days || 0 }}</span>
            <span class="out-stock">出: {{ scope.row.outStock7Days || 0 }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="近30天" align="center" width="120">
        <template slot-scope="scope">
          <div class="stock-change">
            <span class="in-stock">入: {{ scope.row.inStock30Days || 0 }}</span>
            <span class="out-stock">出: {{ scope.row.outStock30Days || 0 }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="日均销量" align="center" width="100" prop="avgDailySales" />
      <el-table-column label="预计可售天数" align="center" width="120">
        <template slot-scope="scope">
          <span :class="getDaysClass(scope.row.estimatedDays)">
            {{ scope.row.estimatedDays > 999 ? '充足' : scope.row.estimatedDays + '天' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="最后入库" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastInTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后出库" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastOutTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 预警商品弹窗 -->
    <el-dialog title="预警商品列表" :visible.sync="warningDialogVisible" width="80%" :close-on-click-modal="false">
      <el-table
        v-loading="warningDialogLoading"
        :data="allWarningProducts"
        border
        style="width: 100%"
      >
        <el-table-column label="商品信息" align="center" min-width="200">
          <template slot-scope="scope">
            <div class="product-info">
              <div class="product-name">{{ scope.row.productName }}</div>
              <div class="product-code">{{ scope.row.productCode }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="SKU信息" align="center" min-width="150">
          <template slot-scope="scope">
            <div class="sku-info">
              <div class="sku-name">{{ scope.row.skuName || '默认规格' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分类/品牌" align="center" width="120">
          <template slot-scope="scope">
            <div>{{ scope.row.categoryName }}</div>
            <div class="text-muted">{{ scope.row.brandName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="当前库存" align="center" width="100">
          <template slot-scope="scope">
            <span :class="getStockClass(scope.row)">{{ scope.row.currentStock }}</span>
          </template>
        </el-table-column>
        <el-table-column label="安全库存" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.safetyStock }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库存状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.stockStatus)" size="mini">
              {{ getStatusText(scope.row.stockStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="健康度" align="center" width="100">
          <template slot-scope="scope">
            <span :style="{ color: getHealthColor(scope.row.healthScore) }">
              {{ Math.min(Math.max(scope.row.healthScore || 0, 0), 100) }}%
            </span>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="warningTotal>0"
        :total="warningTotal"
        :page.sync="warningQueryParams.pageNum"
        :limit.sync="warningQueryParams.pageSize"
        @pagination="handleWarningPagination"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="warningDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStock, getStatistics, getTrend, getWarningProducts, exportStock } from "@/api/statistics/stock";
import { listCategory } from "@/api/fun/category";
import { listBrand } from "@/api/fun/brand";
import * as echarts from 'echarts';

export default {
  name: "StockAnalysis",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存监控表格数据
      stockList: [],
      // 统计数据
      statistics: {},
      // 预警商品
      warningProducts: [],
      // 分类选项
      categoryOptions: [],
      // 品牌选项
      brandOptions: [],
      // 预警商品弹窗相关
      warningDialogVisible: false,
      warningDialogLoading: false,
      allWarningProducts: [],
      warningTotal: 0,
      warningQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productCode: null,
        categoryId: null,
        brandId: null,
        stockStatus: null
      }
    };
  },
  created() {
    this.getList();
    this.getStatistics();
    this.getWarningProducts();
    this.getCategoryOptions();
    this.getBrandOptions();
    this.initChart();
  },
  methods: {
    /** 查询库存监控列表 */
    getList() {
      this.loading = true;
      listStock(this.queryParams).then(response => {
        this.stockList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error('获取库存监控列表失败:', error);
        this.$message.error('获取库存监控列表失败');
        this.loading = false;
      });
    },
    /** 获取统计数据 */
    getStatistics() {
      getStatistics(this.queryParams).then(response => {
        this.statistics = response.data;
      }).catch(error => {
        console.error('获取统计数据失败:', error);
        this.$message.error('获取统计数据失败');
      });
    },
    /** 获取预警商品 */
    getWarningProducts() {
      getWarningProducts(this.queryParams).then(response => {
        // 修复数据结构问题，确保正确获取数组数据
        const data = response.rows || response.data || [];
        this.warningProducts = Array.isArray(data) ? data.slice(0, 5) : [];
      }).catch(error => {
        console.error('获取预警商品失败:', error);
        this.$message.error('获取预警商品失败');
        this.warningProducts = [];
      });
    },
    /** 获取分类选项 */
    getCategoryOptions() {
      listCategory().then(response => {
        this.categoryOptions = response.rows;
      });
    },
    /** 获取品牌选项 */
    getBrandOptions() {
      listBrand().then(response => {
        this.brandOptions = response.rows;
      });
    },
    /** 初始化图表 */
    initChart() {
      this.$nextTick(() => {
        getTrend(this.queryParams).then(response => {
          const chartDom = document.getElementById('trendChart');
          if (!chartDom) {
            console.error('图表容器未找到');
            return;
          }

          const myChart = echarts.init(chartDom);

          // 处理数据，如果没有数据则显示空状态
          let dates = [];
          let inStockData = [];
          let outStockData = [];

          if (response.data && response.data.length > 0) {
            dates = response.data.map(item => item.date);
            inStockData = response.data.map(item => item.inStock || 0);
            outStockData = response.data.map(item => item.outStock || 0);
          } else {
            // 无数据时显示最近7天的空数据
            const today = new Date();
            for (let i = 6; i >= 0; i--) {
              const date = new Date(today);
              date.setDate(date.getDate() - i);
              dates.push((date.getMonth() + 1) + '-' + date.getDate());
              inStockData.push(0);
              outStockData.push(0);
            }
          }

          const option = {
            tooltip: {
              trigger: 'axis'
            },
            legend: {
              data: ['入库', '出库']
            },
            xAxis: {
              type: 'category',
              data: dates
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '入库',
                type: 'line',
                data: inStockData,
                itemStyle: { color: '#67C23A' }
              },
              {
                name: '出库',
                type: 'line',
                data: outStockData,
                itemStyle: { color: '#F56C6C' }
              }
            ],
            // 无数据时显示提示
            graphic: response.data && response.data.length > 0 ? [] : [
              {
                type: 'text',
                left: 'center',
                top: 'middle',
                style: {
                  text: '暂无数据',
                  fontSize: 16,
                  fill: '#999'
                }
              }
            ]
          };

          myChart.setOption(option);
        }).catch(error => {
          console.error('获取库存变动趋势失败:', error);
          this.$message.error('获取库存变动趋势失败');
        });
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getStatistics();
      this.getWarningProducts();
      this.initChart();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('statistics/stock/export', {
        ...this.queryParams
      }, `库存监控_${new Date().getTime()}.xlsx`);
    },
    /** 查看全部预警 */
    viewAllWarnings() {
      this.warningDialogVisible = true;
      this.getAllWarningProducts();
    },
    /** 获取所有预警商品 */
    getAllWarningProducts() {
      this.warningDialogLoading = true;
      getWarningProducts(this.warningQueryParams).then(response => {
        this.allWarningProducts = response.rows;
        this.warningTotal = response.total;
        this.warningDialogLoading = false;
      }).catch(() => {
        this.warningDialogLoading = false;
      });
    },
    /** 预警商品分页 */
    handleWarningPagination(pagination) {
      this.warningQueryParams.pageNum = pagination.page;
      this.warningQueryParams.pageSize = pagination.limit;
      this.getAllWarningProducts();
    },
    /** 获取库存状态样式 */
    getStockClass(row) {
      if (row.stockStatus === '3') return 'danger-text';
      if (row.stockStatus === '2') return 'warning-text';
      return 'success-text';
    },
    /** 获取状态类型 */
    getStatusType(status) {
      const statusMap = {
        '1': 'success',
        '2': 'warning',
        '3': 'danger'
      };
      return statusMap[status] || 'info';
    },
    /** 获取状态文本 */
    getStatusText(status) {
      const statusMap = {
        '1': '正常',
        '2': '预警',
        '3': '缺货'
      };
      return statusMap[status] || '未知';
    },
    /** 获取健康度颜色 */
    getHealthColor(score) {
      // 确保健康度在0-100范围内
      const normalizedScore = Math.min(Math.max(score || 0, 0), 100);
      if (normalizedScore >= 80) return '#67C23A';
      if (normalizedScore >= 50) return '#E6A23C';
      return '#F56C6C';
    },
    /** 获取天数样式 */
    getDaysClass(days) {
      if (days <= 7) return 'danger-text';
      if (days <= 30) return 'warning-text';
      return 'success-text';
    }
  }
};
</script>

<style scoped>
.mb20 {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-card.normal {
  background: linear-gradient(135deg, #67C23A, #85CE61);
}

.stat-card.warning {
  background: linear-gradient(135deg, #E6A23C, #EEBE77);
}

.stat-card.danger {
  background: linear-gradient(135deg, #F56C6C, #F78989);
}

.stat-card.info {
  background: linear-gradient(135deg, #409EFF, #66B1FF);
}

.stat-icon {
  font-size: 40px;
  margin-right: 20px;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
}

.warning-list {
  max-height: 280px;
  overflow-y: auto;
}

.no-data {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.no-data i {
  font-size: 48px;
  margin-bottom: 10px;
  display: block;
}

.no-data p {
  margin: 0;
  font-size: 14px;
}

.warning-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.warning-item:last-child {
  border-bottom: none;
}

.warning-info {
  flex: 1;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.stock-info {
  font-size: 12px;
  color: #666;
}

.product-info .product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-info .product-code {
  font-size: 12px;
  color: #999;
}

.sku-info .sku-name {
  font-weight: bold;
  margin-bottom: 5px;
  color: #409EFF;
}

.sku-info .sku-code {
  font-size: 12px;
  color: #999;
  margin-bottom: 3px;
}

.sku-info .spec-info {
  font-size: 11px;
  color: #666;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
}

.text-muted {
  color: #999;
  font-size: 12px;
}

.stock-change {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.in-stock {
  color: #67C23A;
  font-size: 12px;
}

.out-stock {
  color: #F56C6C;
  font-size: 12px;
}

.health-text {
  text-align: center;
  font-size: 12px;
  margin-top: 5px;
}

.success-text {
  color: #67C23A;
}

.warning-text {
  color: #E6A23C;
}

.danger-text {
  color: #F56C6C;
}
</style>
